const { BaseDatabase, getDbPath } = require('./db');

class CountModel extends BaseDatabase {
	constructor() {
		super(getDbPath('tiktok_data'));
		this.tableName = 'count_record';
		this._initTable();
	}

	// 初始化用户表结构
	_initTable() {
		this.exec(`
			CREATE TABLE IF NOT EXISTS count (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			type INTEGER NOT NULL, -- 类型：1:采集数量 2:已查验数量 3:已上传数量,
			count INTEGER NOT NULL,
			date TEXT NOT NULL
			);	
		`);
		console.log('count_record表初始化完成');
	}

	insert(type, count, date) {
		this.exec(`INSERT INTO count (type, count, date) VALUES (${type}, ${count}, ${date})`);
	}
	
	/**
	 * 更新或插入计数记录
	 * @param {number} type 类型
	 * @param {number} count 计数
	 * @param {string} date 日期
	 */
	async upsertCount(type, count, date) {
		// 先查询是否存在记录
		const existingRecord = this.db.prepare('SELECT count FROM count WHERE type = ? AND date = ?').get(type, date);
		
		if (existingRecord) {
			// 如果存在记录，更新count值
			const newCount = existingRecord.count + count;
			this.db.prepare('UPDATE count SET count = ? WHERE type = ? AND date = ?').run(newCount, type, date);
		} else {
			// 如果不存在记录，插入新记录
			this.db.prepare('INSERT INTO count (type, count, date) VALUES (?, ?, ?)').run(type, count, date);
		}
	}

	/**	
	 * 获取指定日期的计数记录
	 * @param {string} date 日期
	 * @returns 
	 */
	async getCount(date) {
		const res = await this.db.prepare('SELECT * FROM count where date = ?').all(date);
		return res;
	}
}

module.exports = CountModel;
